package com.wujian.love.study.thread;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

/**
 * @ClassName: BoundedHashset
 * @Description: 信号量
 * @Author: wuj
 * @Date: 2021-03-08 15:27
 **/
public class SemaphoreBoundedHashset<T> {


    private final Set<T> set;

    private final Semaphore sem;


    public SemaphoreBoundedHashset(int bound){
        this.set = Collections.synchronizedSet(new HashSet<T>());
        sem = new Semaphore(bound);
    }

    public  boolean add(T o)throws InterruptedException{
        sem.acquire();
        boolean wasAdded = false;

        try{
            wasAdded = set.add(o);
            return wasAdded;
        }finally {
            if(!wasAdded){
                sem.release();
            }
        }
    }

    public boolean remove(Object o){
        boolean wasRemoved = set.remove(o);
        if(wasRemoved){
            sem.release();

        }
        return  wasRemoved;
    }




}
